package com.study.util;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

	public static boolean isEmpty(List value) {
		if (null == value || value.size() == 0) {
			return true;
		}
		return false;
	}

	public static String getStringObj(Object obj) {
		return null == obj | "".equals(obj) ? "" : obj.toString();
	}

	public static String obj2Str(Object obj) {
		return null == obj ? null : obj.toString();
	}

	public static Integer obj2Int(Object obj) {
		return null == obj ? 0 : Integer.parseInt(obj.toString());
	}

	/**
	 * 方法功能：是否为空
	 * 
	 * @param str
	 *            字符串
	 * @return 空：true；否则：false
	 */
	public static boolean isBlank(Object str) {
		if (str == null) {
			return true;
		}
		String s = str.toString().trim();
		return "".equals(s);
	}

	/**
	 * 替换字符串中所有的回车换行为空
	 * 
	 * @param str
	 *            需替换的字符串
	 * @return 无回车换行的字符串
	 */
	public static String replaceEnterToNull(String str) {
		if (null == str || "".equals(str)) {
			return "";
		}
		return str.replaceAll("\n", "").replaceAll("\r", "");
	}

	/**
	 * 
	 * 方法功能：字符串去空格、回车换行
	 * 
	 * @param str
	 * @return
	 */
	public static String filterForPureString(String str) {
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");

		Matcher m = p.matcher(str);
		String pureStr = m.replaceAll("");
		return pureStr;
	}

	public static boolean isChineseStr(String str) {
		// u4E00-u9FA5 汉字unicode范围
		// uFE30-uFFA0 中文标点符号unicode范围
		final String reg = "[\u4E00-\u9FA5]|[\uFE30-\uFFA0]";
		// "[\\p{InCJK Unified Ideographs}&&\\P{Cn}]]";
		Pattern pat = Pattern.compile(reg);
		Matcher mat = pat.matcher(str);
		return mat.find();
	}

	public static String convertToString(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		try {
			return new String(bytes, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// logger.error("convertToString error", e);
			return null;
		}
	}

	public static byte[] convertToBytes(String str) {
		if (str == null) {
			return null;
		}
		try {
			return str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// logger.error("convertToBytes error", e);
			return null;
		}
	}

	/**
	 * 
	 * 方法功能：去空格（将null的字符串返回""）
	 * 
	 * @param str
	 *            字符串
	 * @return
	 */
	public static String trim(String str) {
		if (!isBlank(str)) {
			return str.trim();
		} else {
			return "";
		}
	}

	public static boolean isNumber(String num) {
		return num.matches("[0-9]*");
	}

	public static boolean isNumber(int num) {
		return isNumber("" + num);
	}

	public static boolean isEmail(String email) {
		String emailReg = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

		if (email.matches(emailReg)) {
			return true;
		}

		return false;
	}

	public static String formatFiled(String str) {
		if (null != str) {
			return str.replaceAll("[_\\s-\\.]", "").toLowerCase();
		}
		return null;
	}

	/**
	 * 
	 * 方法功能：是否为手机号码
	 * 
	 * @param phone
	 *            待校验的手机号
	 * @return
	 */
	public static boolean isPhone(String phone) {
		String phoneReg = "^((13[0-9]{1})|147|150|151|152|153|157|158|159|182|183|184|187|188)+\\d{8}$";
		return phone.matches(phoneReg);
	}

	/**
	 * 替换字符串中的手机号码
	 * 
	 * @param str
	 *            字符串
	 * @param phoneNum
	 *            手机号码
	 * @return
	 */
	public static String filterPhoneNum(String str, String phoneNum) {
		if (!StringUtil.isBlank(phoneNum) && phoneNum.length() >= 11) {
			String xNum = phoneNum.substring(0, 3) + "*****" + phoneNum.substring(8);
			String filterStr = str.replaceAll("(" + phoneNum + ")", xNum);
			return filterStr;
		}
		return str;
	}

	/**
	 * 判断通过IMSI拿到值是不是手机号
	 * 
	 * @param String
	 * @return boolean
	 */
	public static boolean isIMSIPhone(String requestParameter) {

		return Pattern.compile("^(1)\\d{10}$").matcher(requestParameter).matches();
	}

	public static boolean isPositiveInteger(String num) {
		return num.matches("[1-9]*");
	}

	public static String reverseNullToEmpty(String str) {
		return str == null ? "" : str;
	}

	/**
	 * 将字符串转换为int。<br>
	 * 如果字符无法转换为数字，则返回null。
	 * 
	 * @param str
	 * @return
	 */
	public static Integer parseInt(String str) {
		try {
			Integer val = Integer.valueOf(str);
			return val;
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 将字符串转换为float。<br>
	 * 如果字符串无法转换为数字，则返回null。
	 * 
	 * @param str
	 * @return
	 */
	public static Float parseFloat(String str) {
		try {
			Float val = Float.valueOf(str);
			return val;
		} catch (Exception ex) {
			return null;
		}
	}

	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static int dateToInt(String date) {
		int time = 0;
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			String timeLong = sf.parse(date).getTime() + "";
			time = Integer.parseInt(timeLong.substring(0, timeLong.length() - 3));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return time;
	}

	public static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	public static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	public static String sign(String jsapi_ticket, String url, String nonce_str, String timestamp) {
		String string1;
		String signature = "";

		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return signature;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	public static String getLinuxLocalIp() throws SocketException {
		String ip = "";
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				String name = intf.getName();
				if (!name.contains("docker") && !name.contains("lo")) {
					for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							String ipaddress = inetAddress.getHostAddress().toString();
							if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
									&& !ipaddress.contains("fe80")) {
								ip = ipaddress;
								System.out.println(ipaddress);
							}
						}
					}
				}
			}
		} catch (SocketException ex) {
			ip = "127.0.0.1";
			ex.printStackTrace();
		}
		return ip;
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}